package com.znsd.r_e_m.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.znsd.r_e_m.bean.Student;
import com.znsd.r_e_m.dao.EsDataGet;
import com.znsd.r_e_m.dao.StudentMapper;
import com.znsd.r_e_m.reader.RedisDataGet;
import com.znsd.r_e_m.utils.RedisUtils;
import org.apache.ibatis.annotations.Insert;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class StudentController {

    @Autowired
    StudentMapper studentMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    RedisDataGet redisDataGet;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private EsDataGet esDataGet;

    @ResponseBody
    @RequestMapping("/saveStudent")
    public int saveStudent(Student student){
        rabbitTemplate.convertAndSend("stuEx","save",student);
        return 1;
    }

    @ResponseBody
    @RequestMapping("/removeStudent")
    public int removeStudent(String ids){
        System.out.println(ids);
        rabbitTemplate.convertAndSend("stuEx","remove",ids);
        return 1;
    }

    @ResponseBody
    @RequestMapping("/updateStudent")
    public int updateStudent(Student student){
        System.out.println(student);
        rabbitTemplate.convertAndSend("stuEx","update",student);
        return 1;
    }

    @ResponseBody
    @RequestMapping("/getStudent")
    public JSONObject getStudent(String keyword, Integer page , Integer rows){
        page-=1;

        System.out.println(page+"=="+rows+"=="+keyword);

        JSONObject jsonObject = new JSONObject();

        String key=page+"-"+rows;
        if(keyword!=null && !"".equals(keyword)){
            List<Student> students = esDataGet.globalSearch(keyword, page, rows);
            int i = esDataGet.globalSearchTotal(keyword);
            jsonObject.put("rows",students);
            jsonObject.put("total",i);
        }else{
            if(redisUtils.exists(key)){
                Object o = redisUtils.get(key);
                List<Student> students = JSONArray.parseArray(o.toString(), Student.class);
               jsonObject.put("rows",students);
               jsonObject.put("total",studentMapper.studentCount());
            }else{
               esDataGet.queryAll(page, rows);

                Object o = redisUtils.get(key);
                List<Student> students = JSONArray.parseArray(o.toString(), Student.class);
                jsonObject.put("rows",students);
                jsonObject.put("total",studentMapper.studentCount());
            }
        }
        return jsonObject;
    }

}